package com.cysyz.mylib.commonservice.resetpasswordbyquestion.impl;

import com.cysyz.mylib.commonservice.resetpasswordbyquestion.GetQuestionAndAnswerAble;
import com.cysyz.mylib.commonservice.resetpasswordbyquestion.ResetPasswordByQuestionAble;
import com.cysyz.mylib.commonservice.resetpasswordbyquestion.RestPasswordByAnswerService;
import com.cysyz.mylib.commonservice.resetpasswordbyquestion.exception.AnswerNotMatchException;
import com.cysyz.mylib.commonservice.servicesupport.CommonServiceSupport;
import com.cysyz.mylib.utils.MD5;

public class ResetPasswordByAnswerServiceImpl extends CommonServiceSupport implements RestPasswordByAnswerService {
	@Override
	public void resetPasswordByQuestion(ResetPasswordByQuestionAble entity, String newPassword, GetQuestionAndAnswerAble... questionAndAnswers) throws AnswerNotMatchException {
		ResetPasswordByQuestionAble entityDB = this.get(entity.getClass(), entity.getId());
		GetQuestionAndAnswerAble[] questionAndAnswersOfDB = entityDB.getQuestionAndAnswers();
		
		boolean oneQaIsMatch = false;
		for (GetQuestionAndAnswerAble qaDB :questionAndAnswersOfDB) {
			for (GetQuestionAndAnswerAble qaInput : questionAndAnswers) {
				if (qaDB.getQuestion().equals(qaInput.getQuestion()) 
					&& qaDB.getAnswer().equals(qaInput.getAnswer())) {
					oneQaIsMatch = true;
					break;
				}
			}
			if (oneQaIsMatch) {
				oneQaIsMatch = false;
			} else {
				throw new AnswerNotMatchException("the answer is not match:question=" + qaDB.getQuestion());
			}
		}
		entityDB.setPassword(MD5.MD5Encode(newPassword));
	}
	
}
